package cj.web.admin.controllers;

import java.io.File;
import java.math.BigDecimal;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.ImageUtils;
import cj.utils.MD5Security;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.admin.dao.AreaDAO;
import cj.web.admin.dao.GameDAO;
import cj.web.admin.dao.PermitDAO;
import cj.web.admin.dao.PermitHistoryDAO;
import cj.web.admin.dao.SchoolDAO;
import cj.web.admin.domain.Area;
import cj.web.admin.domain.Game;
import cj.web.admin.domain.Permit;
import cj.web.admin.domain.School;
import cj.web.admin.util.StringRandom;
import cj.web.constants.GameTypeEnum;
import cj.web.constants.MemuEnum;
import cj.web.constants.PermitStatusEnum;
import cj.web.login.controllers.BaseController;

@Path("/game")
public class GameController extends BaseController{

	private static Logger logger = Logger.getLogger(GameController.class.getName());
	
	@Autowired
	private GameDAO gameDao;
	
	@Autowired
	private PermitDAO permitDao;
	@Autowired
	private PermitHistoryDAO permitHistoryDao;
	@Autowired
	private SchoolDAO schoolDao;
	@Autowired
	private AreaDAO areaDao;
	
	@Get("show")
	public String show(Model model) {
		//MemuEnum
        model.add("MemuEnum",MemuEnum.hdgl);
		return "/views/game/gameList.vm";
	}

	@Post("getList")
	public String queryList(Game game) {
		JSONObject jo = new JSONObject();
		
		List<Game> objs = gameDao.query(game);
		
		for(Game obj:objs){
			obj.setStartDate(DateUtils.getMinusTime(obj.getStartDate(), DateUtils.DATE_FULL_STR, 0));
			obj.setEndDate(DateUtils.getMinusTime(obj.getEndDate(), DateUtils.DATE_FULL_STR, 0));
		}
		
		int size = gameDao.querysize(game);
		jo.put("data", objs);
		jo.put("draw", game.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model){
		model.add("GameType",EnumSet.allOf(GameTypeEnum.class));
		//MemuEnum
        model.add("MemuEnum",MemuEnum.hdgl);
		return "/views/game/gameDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,Game game,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			
			if(GameTypeEnum.MF.getValue().equals(game.getType().toString())){
				game.setPrice(new BigDecimal(0));
			}
			
			game.setCreateUser(returnSessionObj(request).getAccount());
			game.setUpdateUser(returnSessionObj(request).getAccount());
			gameDao.create(game);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id){
		Game obj = gameDao.queryById(id);
		obj.setStartDate(DateUtils.getMinusTime(obj.getStartDate(), DateUtils.DATE_FULL_STR, 0));
		obj.setEndDate(DateUtils.getMinusTime(obj.getEndDate(), DateUtils.DATE_FULL_STR, 0));
		model.add("obj", obj);
		model.add("GameType",EnumSet.allOf(GameTypeEnum.class));
		//MemuEnum
        model.add("MemuEnum",MemuEnum.hdgl);
		return "/views/game/gameEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,Game game,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			if(GameTypeEnum.MF.getValue().equals(game.getType().toString())){
				game.setPrice(new BigDecimal(0));
			}
			game.setUpdateUser(returnSessionObj(request).getAccount());
			gameDao.update(game);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") int id){
		gameDao.deleteById(id);
		return "r:show";
	}
	
	@Post("upload")
	public String upload(@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (!file.isEmpty()) {  
            try {  
                // 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));  
                
                jo.put("filePath", rep.get("filepath")+"/"+fileName);
                
                ImageUtils.scale2(path+"/"+fileName, path+"/s_"+fileName, 368, 640, true);//缩率图		750*432
            } catch (Exception e) {  
                e.printStackTrace();  
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
	
	@Get("createPermitByGId")
	public String createPermitByGId(Model model,@Param("id") int id,HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
		Game obj = gameDao.queryById(id);
			if(obj!=null){
				List<Area> arealis = areaDao.queryAll();
				List<School> schoollis = schoolDao.queryAll();
				
				createPermit(arealis, schoollis, id,request);
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("showGS")
	public String showGS(Model model,@Param("id") int id) {
		Game obj = gameDao.queryById(id);
		model.add("obj", obj);
		//MemuEnum
        model.add("MemuEnum",MemuEnum.hdgl);
		return "/views/game/gameSchoolList.vm";
	}
	
	@Post("getGSList")
	public String queryGSList(School school) {
		JSONObject jo = new JSONObject();
		
		Map rep = new HashMap();
		List<Area> areaObjs = areaDao.queryAll();
		for(Area obj:areaObjs){
			rep.put(obj.getId(), obj.getCode()+":"+obj.getName());
		}
		
		List<School> objs = schoolDao.query(school);
		
		for(School obj:objs){
			String str = rep.get(obj.getAreaId()).toString();
			obj.setAreaCode(str.split(":")[0]);
			obj.setAreaName(str.split(":")[1]);
		}
		
		int size = schoolDao.querysize(school);
		jo.put("data", objs);
		jo.put("draw", school.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	@Get("editGS")
	public String editGS(Model model,@Param("schoolId") int schoolId,@Param("gameId") int gameId){
		School obj = schoolDao.queryById(schoolId);
		
		Area area = areaDao.queryById(obj.getAreaId());
		obj.setAreaName(area.getName());
		obj.setAreaCode(area.getCode());
		model.add("obj", obj);
		model.add("gameId", gameId);
		//MemuEnum
        model.add("MemuEnum",MemuEnum.hdgl);
		return "/views/game/gameSchoolEdit.vm";
	}
	
	//-------------------------------------------------------------------生成参赛证号Old
	/**
	 * 修改人数
	 * @param model
	 * @param schoolId
	 * @param num
	 * @param request
	 * @return
	 */
	@Post("updateGS")
	public String updateGS(Model model,@Param("gameId") int gameId,@Param("schoolId") int schoolId,
			@Param("num") int num,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		jo.put("schoolId", schoolId);
		try {
			Game game = gameDao.queryById(gameId);
			if(game!=null){
				School schoolObj = schoolDao.queryById(schoolId);
				if(schoolObj!=null){
					int beforeNum = schoolObj.getNum();//当前的人数
					int addNum = num;//需要添加的人数
					if(addNum<=0){
						schoolDao.updateNumById(schoolId,num);
						jo.put("returnFlag", Constants.returnObj.returnFlag_true);
						return "@"+jo.toString();
					}
					
					Area areaObj = areaDao.queryById(schoolObj.getAreaId());
					
					int areaId = areaObj.getId();//区域ID
					String areaCode = areaObj.getCode();//区域编号
					String areaName = areaObj.getName();//区域名称
					//学校属于区域
					String schoolCode = schoolObj.getCode();//学校编号
					String schoolName = schoolObj.getName();//学校名称
					String address = schoolObj.getAddress();//学校地址
					
					schoolDao.updateNumById(schoolId,addNum);
					
					for(int i=(beforeNum+1);i<=(beforeNum+addNum);i++){
						String code = StringRandom.formatNum("0000", i);
						
						Permit permitObj =permitDao.queryByCode(areaCode+schoolCode+code, gameId);
						if(permitObj!=null){
							continue;
						}
						
						String returnCode = StringRandom.getStringRandom(8);//回执码
						String pwd = StringRandom.getSixRandom();//密码
						
						Permit permit = new Permit();
						permit.setAreaName(areaName);
						permit.setAreaId(areaId);
						permit.setCode(areaCode+schoolCode+code);
						permit.setGameId(gameId);
						permit.setSchoolId(schoolId);
						permit.setSchoolName(schoolName);
						permit.setAddress(address);
						permit.setPwd(MD5Security.md5(pwd));
//							permit.setPwdShow(Base64.getBase64(pwd));
						permit.setPwdShow(pwd);
						permit.setReturnCode(returnCode);
						permit.setStatus(PermitStatusEnum.YXWSY.getValue());
						permit.setCreateUser(returnSessionObj(request).getAccount());
						permit.setUpdateUser(returnSessionObj(request).getAccount());
						
						permitDao.create(permit);
					}
					
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 复制
	 * @param model
	 * @param gameId
	 * @param request
	 * @return
	 */
	@Post("copyPermit")
	public String copyPermit(Model model,@Param("gameId") int gameId,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		try {
			permitHistoryDao.copy(gameId);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 重新生成
	 * @param model
	 * @param gameId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Post("initPermitByGId")
	public String initPermitByGId(Model model,@Param("gameId") int gameId,HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
		Game obj = gameDao.queryById(gameId);
			if(obj!=null){
				permitDao.removeByGId(gameId);
				
				List<Area> arealis = areaDao.queryAll();
				List<School> schoollis = schoolDao.queryAll();
				
				createPermit(arealis, schoollis, gameId,request);
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 生成参赛证号
	 * @param arealis
	 * @param schoollis
	 * @param gameId
	 * @param request
	 */
	private void createPermit(List<Area> arealis,List<School> schoollis,int gameId,HttpServletRequest request){
		try {
			for(Area areaObj:arealis){
				int areaId = areaObj.getId();//区域ID
				String areaCode = areaObj.getCode();//区域编号
				String areaName = areaObj.getName();//区域名称
				for(School schoolObj:schoollis){
					//学校属于区域
					if(areaId==schoolObj.getAreaId()){
						int schoolId = schoolObj.getId();//学校ID
						String schoolCode = schoolObj.getCode();//学校编号
						String schoolName = schoolObj.getName();//学校名称
						String address = schoolObj.getAddress();//学校名称
						int schoolNum = schoolObj.getNum();//学校人数
						
						for(int i=1;i<=schoolNum;i++){
							String code = StringRandom.formatNum("0000", i);
							
							Permit permitObj =permitDao.queryByCode(areaCode+schoolCode+code, gameId);
							if(permitObj!=null){
								continue;
							}
							
							String returnCode = StringRandom.getStringRandom(8);//回执码随机8位
							String pwd = StringRandom.getSixRandom();//密码
							
							Permit permit = new Permit();
							permit.setAreaName(areaName);
							permit.setAreaId(areaId);
							permit.setCode(areaCode+schoolCode+code);
							permit.setGameId(gameId);
							permit.setSchoolId(schoolId);
							permit.setSchoolName(schoolName);
							permit.setAddress(address);
							permit.setPwd(MD5Security.md5(pwd));
//								permit.setPwdShow(Base64.getBase64(pwd));
							permit.setPwdShow(pwd);
							permit.setReturnCode(returnCode);
							permit.setStatus(PermitStatusEnum.YXWSY.getValue());
							permit.setCreateUser(returnSessionObj(request).getAccount());
							permit.setUpdateUser(returnSessionObj(request).getAccount());
							permitDao.create(permit);
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}